var scripts = [null, "", null];
var grid_sysResource = "#grid-table";
var pager_sysRole = "#grid-pager";
var url = $utils.ajax.setUrl("resource/queryList")
$('.page-content-area').ace_ajax('loadScripts', scripts, function () {
  jQuery(function ($) {
    var appResScope = JSON.parse(localStorage.getItem("appResScope"));
    for (var i = 0; i < appResScope.length; i++) {
      $("#resourceCategory").append("<option value='" + appResScope[i].ITEM_CODE + "'>" + appResScope[i].ITEM_NAME + "</option>");
    }

    var appResType = JSON.parse(localStorage.getItem("appResType"));
    for (var i = 0; i < appResType.length; i++) {
      $("#resourceType").append("<option value='" + appResType[i].ITEM_CODE + "'>" + appResType[i].ITEM_NAME + "</option>");
    }

    $(window).on('resize.jqGrid', function () {
      $(grid_sysResource).jqGrid('setGridWidth', $(".page-content").width());
    })
    var parent_column = $(grid_sysResource).closest('[class*="col-"]');
    $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
      if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
        //setTimeout is for webkit only to give time for DOM changes and then redraw!!!
        setTimeout(function () {
          $(grid_sysResource).jqGrid('setGridWidth', parent_column.width());
        }, 0);
      }
    })
    var optinons = jqSetting(grid_sysResource, pager_sysRole, url);
    optinons.url = url;
    optinons.caption = "资源列表"
    optinons.colNames = ['操作 ', 'ID', '域名', '应用范围', '类型', '引用次数','标签', '来源', '创建时间', '资源图片'];
    optinons.colModel = [
      {name: 'operation', index: '', width: 80, fixed: true, sortable: false, resize: false, formatter: operation},
      {
        display: "RESOURCE_ID",
        name: 'RESOURCE_ID',
        index: 'RESOURCE_ID',
        width: 60,
        sorttype: "int",
        hidden: true,
        editable: true
      },
      {
        display: "域名",
        name: 'DOMAIN_NAME',
        index: 'DOMAIN_NAME',
        width: 90,
        editable: true,
        sorttype: "date",
        hidden: true
      },
      {
        display: "应用范围",
        name: 'CATEGORYNAME',
        index: 'CATEGORYNAME',
        width: 90,
        editable: true,
        sorttype: "date",
        hidden: false
      },
      {display: "类型", name: 'TYPENAME', index: 'TYPENAME', width: 90, editable: true, sorttype: "date", hidden: false},
      {
        display: "引用次数",
        name: 'RESOURCE_COUNT',
        index: 'RESOURCE_COUNT',
        width: 90,
        editable: true,
        sorttype: "date",
        hidden: true
      },
      {
        display: "标签",
        name: 'RESOURCE_LABEL',
        index: 'RESOURCE_LABEL',
        width: 90,
        editable: true,
        sorttype: "date",
        hidden: false

      },
      {
        display: "来源",
        name: 'RESOURCE_SOURCE',
        index: 'RESOURCE_SOURCE',
        width: 90,
        editable: true,
        sorttype: "date",
        hidden: false,
        formatter: source
      },
      {
        display: "创建时间",
        name: 'UPDATE_TIME',
        index: 'UPDATE_TIME',
        width: 150,
        sortable: false,
        editable: false,
        formatter: pickDate
      },
      {
        display: "资源图片",
        name: 'RESOURCE_FILENAME',
        index: 'RESOURCE_FILENAME',
        width: 90,
        editable: true,
        sorttype: "date",
        hidden: false,
        formatter: resourceName
      }
    ];
    jQuery(grid_sysResource).jqGrid(optinons);
    $(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size

    function resourceName(v, o, r) {
      var html = "";
      html = '<a target="_blank" href="'+r.IMAGE_URL + '" title="'+ r.RESOURCE_FILENAME+'" >'
      html = html +  ' <img  width="100%" style="max-height: 100%" src="' + r.IMAGE_URL + '" >';
      html = html + '</a>';
      return html;
    }

    function source(v, o, r) {
      var html = "";
      if (r.RESOURCE_SOURCE == 1) {
        html = '系统';
      } else if (r.RESOURCE_SOURCE == 2) {
        html = 'PC';
      } else if (r.RESOURCE_SOURCE == 3) {
        html = '微信';
      } else if (r.RESOURCE_SOURCE == 4) {
        html = 'APP';
      }
      return html

    }

    function operation(v, o, r) {
      var html = ""
      //html+='<span onclick="goEdit('+r.DOMAIN_ID+')" class="ace-icon fa fa-pencil blue bigger-150 cursor-p tt-cursor pld10 prd10"></span>'
      html += '<span onclick="del(' + r.RESOURCE_ID + ',' + r.RESOURCE_COUNT + ')" class="ace-icon fa fa-trash-o red bigger-150 cursor-p tt-cursor"></span>'
      return html
    }

    $(document).one('ajaxloadstart.page', function (e) {
      $(grid_sysResource).jqGrid('GridUnload');
      $('.ui-jqdialog').remove();
    });

    $('#uploadFile').change(function () {
      $_this = $(this);
      var path = $('#uploadFile').val();
      var formData = new FormData();
      formData.append("file", $("#uploadFile")[0].files[0]);
      formData.append("resourceCategory", 1);
      formData.append("resourceType", 1);
      var urlUploadFile = $utils.ajax.setUrl("upload/uploadFile");
      $.ajax({
        url: urlUploadFile,
        type: "post",
        async: true,
        cache: false,
        processData: false,
        contentType: false,
        data: formData,
        success: function (data) {
          var result = JSON.parse(data);
          if (result.success) {

          }
        },
        error: function () {
          alert("添加图片失败");
        }
      });
    })

  });
});


function search() {
  var params = {}
  params.resourceSource = $("#resourceSource").val();
  params.resourceName = "";
  params.resourceCategory = $("#resourceCategory").val();
  params.resourceType = $("#resourceType").val();
  params.resourceLabel = $("#resourceLabel").val();
  $(grid_sysResource).jqGrid('setGridParam', {
    url: url,
    contentType: 'application/json;charset=utf-8',
    page: 1,
    postData: params
    // 发送数据
  }).trigger("reloadGrid"); // 重新载入
}


function del(id, count) {
  if (count > 0) {
    bootbox.confirm("资源已被关联，确定删除吗", function (result) {
      if (result) {
        var url = $utils.ajax.setUrl("resource/deleteResourceById");
        var params = {}
        params.resourceId = id;
        axios.post(url, params)
          .then(function (response) {
            $(grid_sysResource).trigger("reloadGrid");
          })
          .catch(function (error) {
          });
      }
    });
  } else {
    bootbox.confirm("确定删除吗", function (result) {
      if (result) {
        var url = $utils.ajax.setUrl("resource/deleteResourceById");
        var params = {}
        console.info("id=" + id);
        params.resourceId = id;
        axios.post(url, params)
          .then(function (response) {
            $(grid_sysResource).trigger("reloadGrid");
          })
          .catch(function (error) {
          });
      }
    });
  }

}
